package com.example.dollarShipping.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.dollarShipping.entity.Carrier;
import com.example.dollarShipping.entity.Role;
import com.example.dollarShipping.entity.User;
import com.example.dollarShipping.mapper.CarrierMapper;
import com.example.dollarShipping.mapper.RoleMapper;
import com.example.dollarShipping.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	@Resource
	UserMapper userMapper;

	@Resource
	RoleMapper roleMapper;

	@Resource
	CarrierMapper carrierMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		System.out.println("loadUser,username:"+username);
		QueryWrapper q = new QueryWrapper<>();
		q.eq("user_name",username);
		User user = userMapper.selectOne(q);
		try {
			Role role = roleMapper.selectById(user.getRoleId());
			Carrier c = carrierMapper.selectOne(new QueryWrapper<Carrier>().eq("user_id",user.getId()));
			user.setCarrier(c);
			user.setRole(role);
		}catch (Exception e) {
			System.out.println("e");
			e.printStackTrace();
		}
		return UserDetailsImpl.build(user);
	}

}
